package com.lxj.student_security.service.impl;

import com.lxj.student_security.common.CommonResult;
import com.lxj.student_security.entity.LoginRecord;
import com.lxj.student_security.service.EsLoginRecordService;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

@Service
public class EsLoginRecordServiceImpl implements EsLoginRecordService {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public CommonResult getEsLog(LoginRecord loginRecord) {
        /**
         * 分页查询数据
         */
//        SortBuilder sortBuilder = new FieldSortBuilder("userId").order(SortOrder.ASC); 根据userid排序
        Integer aa = (loginRecord.getPageNum() - 1) * loginRecord.getPageSize();
        Pageable pageable = PageRequest.of(aa,loginRecord.getPageSize());//构建分页数据
        Query query = new NativeSearchQueryBuilder()
                .withQuery(matchQuery("username", loginRecord.getUsername()))
                .withHighlightFields(
                        new HighlightBuilder.Field("username").preTags("<font background color='yellow'>")
                                .postTags("</font>")
                )
                .withPageable(pageable)
                .build();
        SearchHits<LoginRecord> hits = elasticsearchRestTemplate.search(query, LoginRecord.class);
        List<LoginRecord> list = SearchHitToLoginRecord(hits);
        HashMap<String,Object> map = new HashMap<>();
        Long bb = hits.getTotalHits();
        map.put("list",list);
        map.put("number",bb);
        return CommonResult.success(map);
    }

    private List<LoginRecord> SearchHitToLoginRecord(SearchHits<LoginRecord> search) {
        //传过来的参数是es搜索得到的一个结果集SearchHits；
        // 用这个结果集调用getSearchHits方法得到一个泛型是product的SearchHit的List集合
        List<SearchHit<LoginRecord>> searchHits = search.getSearchHits();
        List<LoginRecord> collect = searchHits.stream()
                .map(searchHit -> {
                    LoginRecord content = searchHit.getContent();
                    Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
                    highlightFields.forEach((k, v) -> {
                        StringBuffer temp = new StringBuffer();
                        for (int i = 0; i < v.size(); i++) {
                            temp.append(v.get(i));
                        }
                        String s = temp.toString();
                        try {
                            Field keyField = LoginRecord.class.getDeclaredField(k);
                            keyField.setAccessible(true);
                            keyField.set(content, s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    return content;
                }).collect(Collectors.toList());
        return collect;
    }
}
